import { Injectable, UnauthorizedException } from '@nestjs/common';
import { CreateTeacherDto } from './dto/create-teacher.dto';
import { UpdateTeacherDto } from './dto/update-teacher.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Teacher } from './entities/teacher.entity';
import { In, Repository } from 'typeorm';
import { encrypt } from '../utils/crypto';
import { RolesService } from '../roles/roles.service';
import { menuTree } from '../utils';
import { Menu } from '../menus/entities/menu.entity';

@Injectable()
export class TeacherService {
  constructor(
    private readonly rolesService: RolesService,
    @InjectRepository(Teacher)
    private teacherRepository: Repository<Teacher>,
  ) {}

  async create(createTeacherDto: CreateTeacherDto) {
    const teacher = await this.findTCode(createTeacherDto.t_code);
    if (teacher) {
      return new UnauthorizedException('教师编号重复');
    }
    const list = await this.rolesService.returnRolesServiceEntities(
      createTeacherDto.roleIds,
    );
    createTeacherDto.roles = list;
    // 加密
    createTeacherDto.password = encrypt(
      createTeacherDto.password ? createTeacherDto.password : '123456',
    );
    const res = await this.teacherRepository.create(createTeacherDto);
    return await this.teacherRepository.save(res);
  }

  findAll() {
    return this.teacherRepository.find();
  }

  async findTCode(code: string) {
    return await this.teacherRepository.findOne({ where: { t_code: code } });
  }

  async findDetail(tid: number) {
    const res = await this.teacherRepository
      .createQueryBuilder('teacher')
      .leftJoinAndMapMany('teacher.roles', 'teacher.roles', 'role')
      .leftJoinAndMapMany('role.menus', 'role.menus', 'menus')
      .andWhere('teacher.tid = :tid', { tid })
      .getOne();
    const menus: Menu[] = [];
    res.roles.map((item) => {
      if (item.menus.length) {
        menus.push(...item.menus);
      }
    });
    // 角色
    const roles: { id: number; name: string }[] = res.roles.map((item) => {
      return {
        id: item.id,
        name: item.name,
      };
    });
    // 按钮权限
    const buttonList: string[] = [];
    menus.map((item) => {
      if (item.node_type === 3) {
        buttonList.push(item.menu_code);
      }
    });
    // 菜单列表
    // let menusList: any = [];
    // menusList = menuTree(menus, 0);
    return {
      userInForm: await this.findOne(tid),
      roles,
      buttonList,
      // menusList,
    };
  }

  async findOne(tid: number) {
    return await this.teacherRepository.findOne({ where: { tid } });
  }

  async update(id: number, updateTeacherDto: UpdateTeacherDto) {
    const teacherRes = await this.findOne(id);
    if (!teacherRes?.tid) {
      return new UnauthorizedException('教师不存在！');
    }
    const newStudent = this.teacherRepository.merge(
      teacherRes,
      updateTeacherDto,
    );

    return this.teacherRepository.save(newStudent);
  }

  async remove(id: number) {
    const res = await this.findOne(id);
    if (res?.tid) {
      return await this.teacherRepository.remove(res);
    }
    return new UnauthorizedException('教师不存在！');
  }

  // 根据账号密码查询系统用户
  async loginTeacher(t_name: string, password: string) {
    return this.teacherRepository.findOne({
      relations: ['roles'],
      where: { t_name, password },
    });
  }

  // 返回实体
  async returnTeacherEntities(ids: number[]) {
    return await this.teacherRepository.find({
      where: {
        tid: In(ids),
      },
    });
  }
}
